var cluster = require('cluster');

if (cluster.isMaster) {

	var channelMap = {};

	function handleWorkerMessage(msg) {
		var event = msg['event'];
		var channel = msg['channel'];
		var data = msg['data'];
		if (event === 'subscribe') {
			handleSubscribe.call(this, channel);
		} else if (event === 'unsubscribe') {
			handleUnsubscribe.call(this, channel);
		} else if (event === 'publish') {
			handlePublish.call(this, channel, data);
		}
	}

	function handleSubscribe(channel) {
		var workers = channelMap[channel];
		if (!workers) {
			workers = channelMap[channel] = [];
		}
		var index = workers.indexOf(this);
		if (index < 0) {
			workers.push(this);
		}
	}

	function handleUnsubscribe(channel) {
		var workers = channelMap[channel];
		if (!workers) {
			return;
		}
		var index = workers.indexOf(this);
		if (index >= 0) {
			workers.splice(index, 1);
		}
		if (workers.length === 0) {
			delete workers[channel];
		}
	}

	function handlePublish(channel, message) {
		var workers = channelMap[channel];
		if (workers) {
			for (var i = 0, l = workers.length; i < l; ++i) {
				var worker = workers[i];
				worker.send({
					event: 'publish',
					channel: channel,
					message: message
				});
			}
		}
	}

	cluster.on('listening', function (worker) {
		worker.on('message', handleWorkerMessage);
	});

	cluster.on('exit', function (worker) {
		worker.removeListener('message', handleWorkerMessage);
	});
}
